<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Yingyongbao
 *
 * @author dragon.hu add @2016.3.9
 */
require_once 'BaseChannel.php';

//应用宝    流程特殊，类似苹果的验证流程
class Yingyongbao implements BaseChannel 
{
	static $uristr = "/master/mcGM/payment/Yingyongbao/android";  //应用宝的URI
	
	function __construct() 
	{
		//echo "construct";
	}

	//put your code here
	function android($data) 
	{
		$paymentKey="7076ff89860e6cafb4dee88fa340ae7c"; //微信appkey
		$ret = $this->paymentCallBack($paymentKey, ANDROID);
		echo $ret;
	}

	function ios($data) 
	{
		$paymentKey=""; //
		$ret = $this->paymentCallBack($paymentKey, IOS);
		echo $ret;
	}

	function paymentCallBack($paymentKey, $platform)
	{
		$orderLog = new ChargeOrder();
		$orderLog->log("Yingyongbao", $_REQUEST);
		
		$openid = $_REQUEST['openid'];  //
		$appid = $_REQUEST['appid'];  //
		$ts = $_REQUEST['ts'];  //
		$payitem = $_REQUEST['payitem'];  //
		$token = $_REQUEST['token'];  //
		$billno = $_REQUEST['billno'];  //
		$version = $_REQUEST['version'];  //
		$zoneid = $_REQUEST['zoneid'];  //
		$providetype = $_REQUEST['providetype'];  //
		$amt = $_REQUEST['amt'];  //
		$payamt_coins = $_REQUEST['payamt_coins'];  //
		$pubacct_payamt_coins = $_REQUEST['pubacct_payamt_coins'];  //
		$sig = $_REQUEST['sig'];  //
		
		//构成源串的三个部分
		$mystr1 = "";
		$mystr1 = 'GET';
		
		$mystr2 = "";
		$mystr2 = urlencode(self::$uristr);
		
		$mystr3 = "";
		
		$arr = $_REQUEST;
		ksort($arr);
		foreach ($arr as $k=>&$v)
		{
			if ($k == 'sig')  continue;
			$v = self::getacsiiconv($v);
		}
		foreach ($arr as $k=>$v)
		{
			if ($k == 'sig')  continue;
			$mystr3 .= $k.'='.$v.'&';
		}
		$mystr3 = substr($mystr3, 0, -1);
		$mystr3 = urlencode($mystr3);
		
		$mystr = $mystr1."&".$mystr2."&".$mystr3;
		$paymentKey .= '&';
		
		$mysign = base64_encode(hash_hmac('sha1', $mystr, $paymentKey));
		
		if($sig == $mysign)  
		{ //验证通过
			 
			//进行发货
			if(false == $orderLog->recordOrder(STATUS_SUCCESS, $amt/100, $billno, "yingyongbao", $platform))
			{
				$return['ret'] = 4;
				$return['msg'] = 'other error';
				$orderLog->log("yingyongbao",array("order"=>$billno,"money"=>$amt,"serverresult"=>"faild"));
			}else 
			{
				//支付成功
				$return['ret'] = 0;
				$return['msg'] = 'OK';
				$orderLog->log("yingyongbao",array("order"=>$billno,"money"=>$amt,"serverresult"=>"success"));
			}
			 
		} else {
			//"$sig验证失败"
			$return['ret'] = 4;
			$return['msg'] = urlencode('请求参数错误:(sig)');
			$orderLog->log("yingyongbao","  order:$billno  sign error sign:$sig mysign:$mysign");
		}
		$ret = json_encode($return);
		return urldecode($ret);
	}
	//除了 0~9 a~z A~Z !*() 之外其他字符按其ASCII码的十六进制加%进行表示，例如“-”编码为“%2D”。payitem中，单价如果有小数点“.”，请编码为“%2E”
	static function getacsiiconv($str)
	{
		$targetstr = "";
		$objectstr = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!*()";
		for ($i = 0; $i < strlen($str); $i++)
		{
			$flag = false;
			for ($j = 0; $j < strlen($objectstr); $j++)
			{
				if ($str[$i] == $objectstr[$j])//找到了
				{
					$flag = true;
					break;
				}
			}
			if ($flag)
			{
				$targetstr .= $str[$i];
			}
			else
			{
				$targetstr .= '%'.strtoupper(dechex(ord($str[$i])));
			}
		}
		return $targetstr;
	}
	
	
	/***********************以下是(沙盒)验证的流程****************************/
	function yybverify()
	{
		//1.从客户端发过来的数据
		$orderLog = new ChargeOrder();
		$orderLog->log("Yingyongbao", $_REQUEST);
		
		$session_id = $_REQUEST['session_id'];
		$session_type = $_REQUEST['session_type'];
		
		$data['openid'] = $_REQUEST['openid'];
		$data['openkey'] = $_REQUEST['openkey'];
		if ($session_id == 'openid')
		{
			$data['pay_token'] = $_REQUEST['pay_token'];  //微信不需要pay_token
		}
		$data['appid'] = $_REQUEST['appid'];
		$data['ts'] = time();
		//$data['ts'] = 1458721638;
		//$data['sig'] = $_REQUEST['sig'];
		$data['pf'] = $_REQUEST['pf'];
		$data['pfkey'] = $_REQUEST['pfkey'];
		$data['zoneid'] = $_REQUEST['zoneid'];
		//$data['userip'] = $_REQUEST['userip'];    //可选
		//$data['accounttype'] = $_REQUEST['accounttype'];    //可选
		//$data['format'] = $_REQUEST['format'];    //可选
		
		/**********************角色相关信息**************************/
		$roleid = $_REQUEST['roleid'];
		$serverid = $_REQUEST['serverid'];
		$orderid = $_REQUEST['orderid'];
		$accountid = $_REQUEST['accountid'];
		/********************************************************/
		
		//setcookie("session_id", 'openid');
		//setcookie("session_type", 'kp_actoken');
		//setcookie("org_loc", '/mpay/get_balance_m');
		//setcookie("session_id", 'hy_gameid');
		//setcookie("session_type", 'wc_actoken');
		//setcookie("org_loc", urlencode('/mpay/get_balance_m'));
		
		//$url = "https://openapi.tencentyun.com/mpay/get_balance_m ";
		//$url = "http://119.147.19.43/mpay/get_balance_m";
		//沙箱
		//$url = "http://msdktest.qq.com/mpay/get_balance_m";
		//现网
		$url = "http://msdk.qq.com/mpay/get_balance_m";
		$uri = "/mpay/get_balance_m";
		//$appkey = "81Wm7tD0bnJU79j4";  //手Q的Appkey
		$appkey = "8w7y2EyK8PNtv06224ym67i1SDEQmKda";  //现网Appkey  
		//$appkey = "7076ff89860e6cafb4dee88fa340ae7c";  //微信appkey
		//生成sig  HTTP请求方式 & urlencode(uri) & urlencode(a=x&b=y&...)
		ksort($data);
		$tmpstr = "";
		foreach ($data as $k=>$v)
		{
			$tmpstr .= $k.'='.$v.'&';
		}
		$tmpstr = substr($tmpstr, 0, -1);
		//var_dump($tmpstr);
		$tmpsig = 'GET&'.rawurlencode($uri).'&'.rawurlencode($tmpstr);
		$tmpappkey = $appkey.'&';
		$mysign = base64_encode(hash_hmac('sha1', $tmpsig, $tmpappkey, true));
		//var_dump($tmpsig);
		//var_dump($mysign);
		//exit();
		$mysign = rawurlencode($mysign);
		$data['sig'] = $mysign;
		//var_dump($_COOKIE);
		//exit();
		$session_id == 'openid' ? $url .= '?'.'appid='.$data['appid'].'&openid='.$data['openid'].'&openkey='.$data['openkey'].'&pay_token='.$data['pay_token'].
			'&pf='.$data['pf'].'&pfkey='.$data['pfkey'].'&ts='.$data['ts'].'&zoneid='.$data['zoneid'].'&sig='.$data['sig'] : $url .= '?'.'appid='.$data['appid'].'&openid='.$data['openid'].'&openkey='.$data['openkey'].
			'&pf='.$data['pf'].'&pfkey='.$data['pfkey'].'&ts='.$data['ts'].'&zoneid='.$data['zoneid'].'&sig='.$data['sig'];
		
		//var_dump($data);
		//var_dump($url);
		//2.发给应用宝提供的地址进行沙盒验证
		//$res = iosvpost($url);
		
		//初始化chrl
		/*$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		//执行并获取HTML文档内容
		$res = curl_exec($ch);
		//释放curl句柄
		curl_close($ch);*/
		
		//用curl方式发起http请求，带上cookie
		$ch = curl_init ($url);
		// 设置获取数据返回
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
		// 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
		curl_setopt ( $ch, CURLOPT_BINARYTRANSFER, true );
		//$session_id= 'openid';
		//$session_type= 'kp_actoken';
		//$session_id= 'hy_gameid';
		//$session_type= 'wc_actoken';
		//cookie中设置查询余额api的url
		$org_loc='/mpay/get_balance_m';
		$cookie="session_id=$session_id;session_type=$session_type;org_loc=$org_loc";
		//var_dump($cookie);
		curl_setopt ($ch, CURLOPT_COOKIE , $cookie );
		$res = curl_exec ( $ch );
		
		$dataarr = json_decode(urldecode($res), true);
		$nowtime = time();
		
		if ($dataarr['ret'] == 0)
		{
			//此玩家之前的充值总数
			$sql = "SELECT SUM(money) AS num FROM {pre}payment WHERE accountid = $accountid AND channel='yingyongbao' AND platform=1";
			require (CONFIGPATH . 'db.php');
			$tmpdb = new Database($config['payment_db']);
			$row = $tmpdb->one($sql);
			//var_dump($sql);
			//var_dump($row);
			//exit();
			if(!isset($row['num']))
			{
				$row['num'] = 0;
			}
			$money = $dataarr['save_amt']/10 - $row['num'];    //save_amt为Q点的数量
			//var_dump($money);
			//var_dump($orderid);
			//通过orderid是否为空来判定是充值还是登陆
			if ($orderid == 'null' && $money > 0)  //补单流程!!!!!!
			{
				$orderid = "yyborder_".$data['openid'].'_'.$nowtime;  //拼接自己的orderid
				//var_dump($orderid);
				$return = $this->insertOrder($tmpdb, $orderLog, $money, $orderid, $serverid, $roleid, $accountid,  "yingyongbao", ANDROID);
				if ($return)
				{
					$ret = "success";
					$orderLog->log("yingyongbao", array("order"=>$orderid,"money"=>$money,"message"=>$dataarr['message'],"serverresult"=>"resupply order success"));
				}
				else
				{
					$ret = "failure";
					$orderLog->log("yingyongbao", array("order"=>$orderid,"money"=>$money,"message"=>$dataarr['message'],"serverresult"=>"resupply order failed"));
				}
			}
			else  //一般充值流程!!!!!
			{
				//进行发货
				if(false == $orderLog->recordOrder(STATUS_SUCCESS, $money, $orderid, "yingyongbao", ANDROID))
				{
					$ret="failure";
					$orderLog->log("yingyongbao",array("order"=>$orderid,"money"=>$money,"message"=>$dataarr['message'],"serverresult"=>"faild"));
				}else
				{
					//支付成功
					$ret="success";
					$orderLog->log("yingyongbao",array("order"=>$orderid,"money"=>$money,"message"=>$dataarr['message'],"serverresult"=>"success"));
				}
			}
		}
		else
		{
			$ret = "failure";
			$orderLog->log("yingyongbao",array("order"=>$orderid,"ret"=>$dataarr['ret'],"msg"=>$dataarr['msg'],"serverresult"=>"sign error"));
		}
		echo $ret;
	}
	
	function insertOrder($paydb, $orderlog, $money, $orderid, $serverid, $roleid, $accountid, $channelid, $platform,$thirdorderid='')
	{
		$nowtime = date('Y-m-d H:i:s', time());
		$sql = "INSERT INTO {pre}payment(orderid,serverid,roleid,accountid,create_time,status,channel,platform,appid,money,finish_time,product_id) VALUES
        ('$orderid','$serverid','$roleid','$accountid','$nowtime','4','$channelid','$platform','0','$money','$nowtime','3')";  //按产品3也就是6元卡来补，product_id为3一定不能在表dynamic_act_charge中删除！！！
        $res = $paydb->execute($sql);
		if ($res == false)
		{
			$orderlog->log("error", "execute sql failed! ".$sql);
			return false;
		}
        
		$serverInfo = $paydb->one("SELECT * FROM {pre}areasample WHERE `id`='" .$serverid. "'");
		$one['orderid'] = (string) $orderid;
		$one['roleid'] = (int) $roleid;
	    $one['channel'] = (string) $channelid;
		$one['money'] = (string) $money;
		$one['platform'] = (int) $platform;
		$one['finish_time'] = (string)$nowtime;
		$one['product_id'] = (int)3;
		
		//第几次充值
		$paytimes = 0;
		$sql = "SELECT * FROM {pre}payment WHERE serverid = ".$serverid." AND roleid='".$roleid."'";
		$paydb->query($sql);
		$rolepayarr = array();
		while ($n = $paydb->get_array())
		{
			$rolepayarr[] = $n;
		}
		for ($i = 0; $i < count($rolepayarr); $i++)
		{
			if (isset($rolepayarr[$i]['money']))
			{
				$paytimes += 1;
			}
		}
		
		$one['paytimes'] = $paytimes;  //累计支付次数
		$datas[] = $one;
		$json_str = json_encode($datas);
		$json_str = str_replace(" ", "%20", $json_str);
		
		$strResult = vpost($serverInfo['host'] . "json_str=$json_str&action=45", 10);     //请求游戏服务器发放充值
		//推送游戏服务器超时或者失败
		if ($strResult === FALSE || $strResult=="fail") {
			//echo "error:area sending fail ";
			//写log
			$tmpstr = http_build_query($one);
			$orderlog->log("error", "post error!!!".$tmpstr);
			return false;
		}
		return true;
	}
	/********************************应用宝礼包*****************************************/
	function yybgetgift()
	{
		//1.发过来的数据,记录以便以后对账
		$dataarr = $_REQUEST;
		$str = "openid=".$dataarr['openid']." taskid=".$dataarr['taskid']." awardid=".$dataarr['awardid'].
		" billno=".$dataarr['billno']." timestamp=".$dataarr['timestamp']." appid=".$dataarr['timestamp'].
		" action=".$dataarr['action']." area=".$dataarr['area']." pkey=".$dataarr['pkey']." sig=".$dataarr['sig'];
		log_message($str, "yingyongbao");
		//var_dump($dataarr);
		$result = array();
		if (time() - $dataarr['timestamp'] > 5*60 || $dataarr['appid'] != '1105224370')  //开发商收到请求后需验证timestamp与当前请求是否超过5分钟，如果超过5分钟，可认为请求无效直接丢弃
		{
			$result['ret'] = 1;  //请求无效
			$result['msg'] = urlencode('请求无效');
			$ret = json_encode($result);
			return urldecode($ret);
		}
		//sig验证
		$uri = "/master/mcGM/payment/Yingyongbao/yybgetgift";
		$appkey = "81Wm7tD0bnJU79j4";  //手Q的Appkey
		ksort($dataarr);
		$tmpstr = "";
		foreach ($dataarr as $k=>$v)
		{
			$tmpstr .= $k.'='.$v.'&';
		}
		$tmpstr = substr($tmpstr, 0, -1);
		//var_dump($tmpstr);
		$tmpsig = 'GET&'.rawurlencode($uri).'&'.rawurlencode($tmpstr);
		$tmpappkey = $appkey.'&';
		$mysign = base64_encode(hash_hmac('sha1', $tmpsig, $tmpappkey, true));
		//var_dump($tmpsig);
		//var_dump($mysign);
		//exit();
		if ($dataarr['sig'] != $mysign)
		{
			$result['ret'] = 3;  //sig参数错误
			$result['msg'] = urlencode('sig参数错误');
			$ret = json_encode($result);
			return urldecode($ret);
		}
		//pkey验证
		if ($dataarr['pkey'] != md5($dataarr['openid'].$appkey.$dataarr['timestamp']))
		{
			$result['ret'] = 2;  //请求参数错误
			$result['msg'] = urlencode('pkey验证错误');
			$ret = json_encode($result);
			return urldecode($ret);
		}		
		
		$accountname = $dataarr['openid'];
		//通过account表找到accountid
		$conn = new Database($config['center_db']);
		$sql = "SELECT * FROM account WHERE platform = 'yingyongbao' AND name = '$accountname'";
		$one = $conn->one($sql);
		$accountid = $one['id'];
		$logconn = new Database($config['log_db']);
		$sql = "SELECT * FROM rolecreate WHERE account = '$accountid'";
		$one = $logconn->one($sql);
		if (empty($one))
		{
			$result['ret'] = 101;  //用户尚未在应用创建角色
			$result['msg'] = urlencode('用户尚未在应用创建角色');
			$ret = json_encode($result);
			return urldecode($ret);
		}
		//此账号是否领取过这个礼包
		$gmconn = new Database($config['db']);
		$sql = "SELECT * FROM yyb_giftstatus WHERE accountid = '$accountid' AND giftbagtype = '"
				.$dataarr['taskid']."' AND giftbagstatus = 1";  //!!!!!
		$one = $gmconn->one($sql);
		if (isset($one))
		{
			$result['ret'] = 102;  //该步骤奖励已发放过
			$result['msg'] = urlencode('该步骤奖励已发放过');
			$ret = json_encode($result);
			return urldecode($ret);
		}
		
		//所有判断都是只针对此账号下最近登录的角色
		$sql = "SELECT * FROM rolelogin WHERE account = '$accountid' ORDER BY operation_time DESC";
		$one = $logconn->one($sql);
		if (isset($one))
		{
			if ($one['rolelv'] < $dataarr['taskid'])  //!!!!!
			{
				$result['ret'] = 104;  //玩家不符合领取条件
				$result['msg'] = urlencode('玩家不符合领取条件');
				$ret = json_encode($result);
				return urldecode($ret);
			}
			
			//继续  $one['server_id']; $one['role_id']; $one['rolelv'];  给此区此角色发奖励，并返回成功，存表
			//a.发放奖励
			$tmpret = self::sendGiftToPlayer($conn, $one['server_id'], $one['role_id'], $dataarr['taskid']);
			//b.记录存表
			if ($tmpret)
			{
				$nowtime = date("Y-m-d H:i:s", time());
				$sql = "INSERT INTO yyb_giftstatus(accountid, serverid, roleid, giftbagtype, giftbagstatus, finishtime) VALUES(".
				$accountid.", ".$one['server_id'].", ".$one['role_id'].", '".$dataarr['taskid']."', 1, '$nowtime')";  //!!!!!
				if($gmconn->execute($sql))
				{
					$result['ret'] = 0;  //成功
					$result['msg'] = urlencode('步骤完成');
					$ret = json_encode($result);
					return urldecode($ret);
				}
			}
		}
		$result['ret'] = 103;  //奖励发放失败
		$result['msg'] = urlencode('角色未登录过');
		$ret = json_encode($result);
		return urldecode($ret);
	}
	
	/*
	 * 发放奖励的接口
	 *@param $conn为account库的连接
	 *@param $serverid为发送的服务器id
	 *@param $roleid为发送的角色id
	 *@param $gifttype为礼包类型
	 *@return 成功true，失败false
	 */
	static function sendGiftToPlayer($conn, $serverid, $roleid, $gifttype)
	{
		//获取到奖励物品信息
		$dynconn = getTmpDbConnect(PLATFORM_ALL, 'all', $serverid, DBTYPE_DYNAMIC);
		//dynamic_activity_level_mail领取条件不要求可动态修改，而且只在游戏后台用，所以不用在游戏服中加对应逻辑
		$sql = "SELECT giftbag_id FROM dynamic_activity_level_mail WHERE value = $gifttype";  //!!!!!
		$one = $dynconn->one($sql);
		$giftbag_id = $one['giftbag_id'];
		
		$rowdata = array();
		$i = 0;
		$sql = "SELECT * FROM dynamic_giftbagdetail WHERE giftbagid = $giftbag_id";
		$conn->query($sql);
		while ($n = $conn->get_array())
		{
			$rowdata['item'][$i] = $n['objectid'];
			$rowdata['amount'][$i] = $n['maxcount'];
			$rowdata['equiplevel'][$i] = 0;  //装备等级，默认置0
			$i++;
		}
		
		$strparam = "";
		$i = 0;
		while ((!empty($rowdata["item"][$i])) && (!empty($rowdata["amount"][$i]))) {
			$strparam .= "item$i=" . $rowdata['item'][$i]
			."&amount$i=" . $rowdata['amount'][$i]
			."&equiplv$i=" . $rowdata['equiplevel'][$i]
			."&";
			$i++;
		}
		
		$sendData = array();	 
		//填充基本信息
		$sendData['mail_title'] = "邮件标题";    //这个要写成什么样
		$sendData['keep_time'] = -1; //由游戏服来修改时间
		$sendData['mail_content'] = "邮件内容";    //这个要写成什么样
		$sendData['receiver_id'] = $roleid;
		
		$allurl = get_area_list_url();
		$host = $allurl[$serverid];
		$strUrl = $host . array_to_stringparam($sendData) . $strparam . "action=15";  //!!!!!注意权限过滤
		//print_r($strUrl);
		//exit(0);
		$strResult = vpost($strUrl);
		if ($strResult == 1 || $strResult == 4)  //1是发送成功，4是转为离线发送
		{
			return true;
		}
		return false;
	}
}
